package com.qxzn.module.mine.fragment;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.lmc.me.FaqActivity;
import com.lmc.me.FeedbackActivity;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.RobotDeviceListBean;
import com.qxzn.app.bean.UserDetails;
import com.qxzn.app.page.BaseFragment;
import com.qxzn.app.page.robot.RobotHelper;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;
import com.qxzn.module.mine.activity.AboutActivity;
import com.qxzn.module.mine.activity.EmergencyContactActivity;
import com.qxzn.module.mine.activity.FamilyMemberActivity;
import com.qxzn.module.mine.activity.MoreSettingsActivity;
import com.qxzn.module.mine.activity.UserInfoActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 我的页面
 */
public class MineFragment extends BaseFragment {

    @BindView(R2.id.tv_user_name)
    TextView tvUser;
    @BindView(R2.id.tv_robot_id)
    TextView tvDeviceId;
    @BindView(R2.id.tv_robot_name)
    TextView tvNameXiaopai;
    @BindView(R2.id.no_robot_prompt_layout)
    View noRobotPromptLayout;
    @BindView(R2.id.iv_user_head)
    ImageView userHead;

    private RobotHelper robotHelper;

    @Override
    protected int initLayout() {
        return R.layout.fragment_mine;
    }


    @Override
    protected void initView() {
        updateUserInfo();
        setDeviceMsg(SharePreferenceUtil.getDeviceId(getActivity()), SharePreferenceUtil.getDeviceName(getActivity()));
    }

    private void updateUserInfo() {
        String nickname = SharePreferenceUtil.getNickname(getActivity());
        if (TextUtils.isEmpty(nickname))
            nickname = SharePreferenceUtil.getUserName(getActivity());
        tvUser.setText(nickname);
        Glide.with(this).load(SharePreferenceUtil.getPortrait(getContext())).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.drawable.user_head).error(R.drawable.user_head)).into(userHead);
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == Constant.EventBusId.SWITCH_DEVICE_ID) {
            setDeviceMsg(SharePreferenceUtil.getDeviceId(getActivity()), SharePreferenceUtil.getDeviceName(getActivity()));
        } else if (busBean.getId() == Constant.EventBusId.UPDATE_USER_INFO) {
            updateUserInfo();
        } else if (busBean.getId() == Constant.EventBusId.GET_DEVICE) {
            getRobots();
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        robotHelper = new RobotHelper(getActivity());
        getUserDetail();
        getRobots();
    }

    private void getRobots() {
        HttpRequest.getService().getRobotDeviceList().enqueue(new Callback<RobotDeviceListBean>() {
            @Override
            public void onResponse(Call<RobotDeviceListBean> call, Response<RobotDeviceListBean> response) {
                RobotDeviceListBean baseBean = response.body();
                if (baseBean.getCode() == 200) {
                    List<RobotDeviceListBean.DataBean> deviceList = baseBean.getData();
                    String name = "";
                    String id = "";
                    if (deviceList != null) {
                        if (deviceList.size() > 0) {
                            for (RobotDeviceListBean.DataBean dataBean : deviceList) {
                                if ("1".equals(dataBean.getCurrent())) {
                                    name = dataBean.getName();
                                    id = dataBean.getDevice_id();
                                }
                            }
                            if (TextUtils.isEmpty(id)) {
                                RobotDeviceListBean.DataBean dataBean = deviceList.get(0);
                                switchRobot(dataBean.getDevice_id(), dataBean.getName());
                            }
                        }
                    }
                    SharePreferenceUtil.setDeviceId(getActivity(), id);
                    SharePreferenceUtil.setDeviceName(getActivity(), name);
                    EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.SWITCH_DEVICE_ID).build());
                } else if (!TextUtils.isEmpty(baseBean.getMsg())) {
                    ToastUtil.showTextToast(getContext(), baseBean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<RobotDeviceListBean> call, Throwable t) {
                ToastUtil.showTextToast(getContext(), getString(R.string.network_error));
            }
        });
    }


    private void switchRobot(String deviceId, String deviceName) {
        JSONObject params = new JSONObject();
        params.put("device_id", deviceId);
        params.put("username", SharePreferenceUtil.getUserName(getActivity()));
        HttpRequest.getService().changeRobot(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean baseBean = response.body();
                hideProgress();
                if (baseBean != null) {
                    if (baseBean.getCode() == 200) {
                        SharePreferenceUtil.setDeviceId(getContext(), deviceId);
                        SharePreferenceUtil.setDeviceName(getContext(), deviceName);
                        EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.SWITCH_DEVICE_ID).build());
                        return;
                    }
                }
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    ToastUtil.showTextToast(getContext(), baseBean.getMsg());
                } else {
                    ToastUtil.showTextToast(getContext(), "切换失败，请重试");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                ToastUtil.showTextToast(getContext(), getString(R.string.network_error));
            }
        });
    }

    private void getUserDetail() {
        JSONObject params = new JSONObject();
        params.put("username", SharePreferenceUtil.getUserName(getContext()));
        HttpRequest.getService().getUserInfoDetail(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean<UserDetails>>() {
            @Override
            public void onResponse(Call<BaseBean<UserDetails>> call, Response<BaseBean<UserDetails>> response) {
                BaseBean<UserDetails> bean = response.body();
                if (bean != null) {
                    if (bean.getCode() == 200) {
                        UserDetails userDetails = bean.getData();
                        SharePreferenceUtil.setPortrait(getContext(), HttpRequest.BASE_URL + userDetails.headportrait);
                        SharePreferenceUtil.setPhone(getContext(), userDetails.mobile);
                        SharePreferenceUtil.setNickname(getContext(), userDetails.niname);
                        EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.UPDATE_USER_INFO).build());
                    } else {
                        error();
                    }
                }
            }

            private void error() {
                ToastUtil.showTextToast(getContext(), getString(R.string.network_error));
            }

            @Override
            public void onFailure(Call<BaseBean<UserDetails>> call, Throwable t) {
                error();
            }
        });
    }

    @OnClick({R2.id.rl_user_head,
            R2.id.news_center, R2.id.feed_back_app, R2.id.faq_app, R2.id.about_app,
            R2.id.member_btn, R2.id.emergency_contact_btn, R2.id.more_settings_btn,
            R2.id.frame_robot, R2.id.btn_add_robot})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) {
            return;
        }
        int i = view.getId();
        if (i == R.id.rl_user_head) {
            // 用户信息
            startActivity(UserInfoActivity.class);
        } else if (i == R.id.frame_robot) {
            // 切换机器人
            robotHelper.startSwitchRobot(tvNameXiaopai.getText().toString().trim(), 1);
        } else if (i == R.id.btn_add_robot) {
            // 添加机器人
            robotHelper.startAddRobot();
        } else if (i == R.id.member_btn) {
            // 家庭成员
            startActivity(FamilyMemberActivity.class);
        } else if (i == R.id.emergency_contact_btn) {
            // 紧急联系人
            startActivity(EmergencyContactActivity.class);
        } else if (i == R.id.more_settings_btn) {
            // 更多设置
            startActivity(MoreSettingsActivity.class);
        } else if (i == R.id.news_center) {
            // 消息中心
            startActivity(new Intent().setComponent(new ComponentName(getActivity(), "com.qxzn.module.home.activity.NewsActivity")));
        } else if (i == R.id.feed_back_app) {
            // 意见反馈
            startActivity(FeedbackActivity.class);
        } else if (i == R.id.faq_app) {
            // 常见问题
            startActivity(FaqActivity.class);
        } else if (i == R.id.about_app) {
            // 关于奇信康派
            startActivity(AboutActivity.class);
        }
    }

    private void setDeviceMsg(String deviceId, String deviceName) {
        if (TextUtils.isEmpty(deviceId)) {
            noRobotPromptLayout.setVisibility(View.VISIBLE);
        } else {
            noRobotPromptLayout.setVisibility(View.GONE);
            tvDeviceId.setText("小π号：" + deviceId);
            tvNameXiaopai.setText(deviceName);
        }
    }
}
